package com.edu.ad.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.api.entity.ad.PromotionAd;
import com.edu.ad.service.PromotionAdService;
import com.edu.ad.mapper.PromotionAdMapper;
import com.edu.api.entity.common.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 *
 */
@Service
public class PromotionAdServiceImpl extends ServiceImpl<PromotionAdMapper, PromotionAd>
    implements PromotionAdService{

    @Autowired
    PromotionAdMapper promotionAdMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public synchronized List<PromotionAd> getAdsBySpaceId(int spaceId) {
        if (redisTemplate.opsForValue().get("promotionAdList"+spaceId) == null)
            redisTemplate.opsForValue().set("promotionAdList"+spaceId,promotionAdMapper.getAdsBySpaceId(spaceId));
        return (List<PromotionAd>)redisTemplate.opsForValue().get("promotionAdList"+spaceId);
    }

    @Override
    public ResponseDTO updateAdStatus(Integer id,String spaceId, String status,String startTime,String endTime) {
        PromotionAd ad = new PromotionAd();
        ad.setId(id);
        ad.setStatus(status);
        promotionAdMapper.updateById(ad);
        if ("0".equals(status) && TimeUtil.valueOf(startTime).before(TimeUtil.getTimeDate()) && TimeUtil.valueOf(endTime).after(TimeUtil.getTimeDate())){
            redisTemplate.delete("promotionAdList"+spaceId);
        }
        if ("1".equals(status) && TimeUtil.valueOf(startTime).before(TimeUtil.getTimeDate()) && TimeUtil.valueOf(endTime).after(TimeUtil.getTimeDate())){
            redisTemplate.delete("promotionAdList"+spaceId);
        }
        return new ResponseDTO(Code.SAVE_OK,"修改状态成功",null);
    }

    @Override
    public ResponseDTO addOrUpdateBackStageAd(PromotionAd ad, HttpServletRequest request) {
        try {
            QueryWrapper<PromotionAd> queryWrapper = new QueryWrapper();
            if (ad.getId()==null){
                queryWrapper.eq("name",ad.getName()).ge("end_time", TimeUtil.getTime());
                if (!promotionAdMapper.selectList(queryWrapper).isEmpty()){
                    return new ResponseDTO(Code.SAVE_ERR,"广告名重复",null);
                }
                promotionAdMapper.saveAd(ad);
                return new ResponseDTO(Code.SAVE_OK,"添加成功",null);
            }else {
                queryWrapper.eq("name",ad.getName()).ne("id",ad.getId());
                if (!promotionAdMapper.selectList(queryWrapper).isEmpty()){
                    return new ResponseDTO(Code.SAVE_ERR,"广告名重复",null);
                }
                QueryWrapper<PromotionAd> adQueryWrapper = new QueryWrapper<>();
                adQueryWrapper.eq("id",ad.getId());
                PromotionAd promotionAd = promotionAdMapper.selectOne(adQueryWrapper);
                promotionAdMapper.updateById(ad);
                redisTemplate.delete("promotionAdList"+promotionAd.getSpaceId());
                //修改广告位时
                if (!ad.getSpaceId().equals(promotionAd.getSpaceId()))
                    redisTemplate.delete("promotionAdList"+ad.getSpaceId());

                return new ResponseDTO(Code.SAVE_OK,"修改成功",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseDTO(Code.SAVE_OK,"操作失败",null);
        }
    }

    @Override
    public ResponseDTO getAllAd(Pageable pageable, PromotionAd ad) throws ParseException {
        QueryWrapper<PromotionAd> queryWrapper = new QueryWrapper<>();
        Date parse = null;
        Date parse2 = null;
        if (!ad.getCreateTime().equals("NaN-NaN-NaN")){
            parse = new SimpleDateFormat("yyyy-MM-dd").parse(ad.getCreateTime());
            parse2 = new SimpleDateFormat("yyyy-MM-dd").parse(ad.getUpdateTime());
        }
        queryWrapper.eq(!"".equals(ad.getSpaceId()),"space_id",ad.getSpaceId()).eq(!"".equals(ad.getStatus()),"status",ad.getStatus()).like("name",ad.getName())
                .ge(!"NaN-NaN-NaN".equals(ad.getCreateTime()),"create_time",parse)
                .le(!"NaN-NaN-NaN".equals(ad.getUpdateTime()),"update_time",parse2);


        if (ad.getStartTime().equals("1")){
            queryWrapper.and(wrapper -> wrapper.le("start_time",TimeUtil.getTime()).ge("end_time",TimeUtil.getTime()));
        }else if (ad.getStartTime().equals("2")){
            queryWrapper.and(wrapper -> wrapper.le("end_time",TimeUtil.getTime()));
        }else if (ad.getStartTime().equals("3")){
            queryWrapper.and(wrapper -> wrapper.ge("start_time",TimeUtil.getTime()));
        }
        long total = promotionAdMapper.selectCount(queryWrapper);
        long pages = 0;
        if(total>0){
            //计算总页码
            pages = total % pageable.getSize() == 0 ? total / pageable.getSize() : total / pageable.getSize() + 1;
            //页码修正
            pageable.setPage(pageable.getPage() < 1 ? 1 : pageable.getPage());
            pageable.setPage(pageable.getPage() > pages ? pages : pageable.getPage());
            //起始下标
            pageable.setIndex((pageable.getPage() - 1) * pageable.getSize());
        }else{
            pageable.setPage(0);
            pageable.setIndex(0);
        }

//        Page<PromotionAd> adPage = new Page<>(pageable.getPage(), pageable.getSize());
//        Page<PromotionAd> spacePage = promotionAdMapper.selectPage(adPage, queryWrapper);
//        spacePage.setTotal(total);
//        spacePage.setPages(pageable.getPage());
//        spacePage.setSize(pageable.getSize());
//        System.err.println(spacePage.getRecords());
        Page<PromotionAd> spacePage = new Page(promotionAdMapper.getAllAd(pageable,ad), pageable.getPage(), total, pages);

        return new ResponseDTO(Code.GET_OK,"成功",spacePage);
    }

    @Override
    public ResponseDTO deleteAdByIds(List<Integer> ids) {
        promotionAdMapper.deleteAdByIds(ids);
        List<Integer> delIds = promotionAdMapper.getSpaceByAdIds(ids);
        for (int i = 0; i < delIds.size(); i++) {
            redisTemplate.delete("promotionAdList"+delIds.get(i));
        }
        return new ResponseDTO(Code.DELETE_OK,"成功",null);
    }
}




